package com.weishenai.customerassistant.controller.sys;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weishenai.customerassistant.common.dto.PassDto;
import com.weishenai.customerassistant.common.Const;
import com.weishenai.customerassistant.common.Result;
import com.weishenai.customerassistant.controller.BaseController;
import com.weishenai.customerassistant.entity.sys.SysRoleEntity;
import com.weishenai.customerassistant.entity.sys.SysUserEntity;
import com.weishenai.customerassistant.entity.sys.SysUserRoleEntity;
import com.weishenai.customerassistant.service.SysRoleService;
import com.weishenai.customerassistant.service.SysUserRoleService;
import com.weishenai.customerassistant.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author weishenai
 * @since 2021-11-27
 */
@Api(tags = "管理系统 用户管理")
@Slf4j
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {
    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Value("${file.iconPath}")
    private String path;

    @ApiOperation("获取用户信息")
    @ApiImplicitParam(name = "id", value = "用户id")
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result getUserInfo(@PathVariable("id") Long id) {
        SysUserEntity sysUser = sysUserService.getById(id);
        Assert.notNull(sysUser, "找不到管理员");

        List<SysRoleEntity> sysRoles = sysRoleService.ListRolesByUserId(id);
        sysUser.setSysRoles(sysRoles);
        return Result.success(sysUser);
    }

    @ApiOperation("用户列表")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result getUserList(@RequestParam(required = false) String name, @RequestParam Integer currentPage, @RequestParam Integer pageSize) {
        Page<SysUserEntity> pageData = sysUserService.selectPage(name, currentPage, pageSize);
        pageData.getRecords().forEach(u -> {
            u.setSysRoles(sysRoleService.ListRolesByUserId(u.getId()));
        });
        return Result.success(pageData);
    }


    @ApiOperation("添加用户")
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result save(@Validated @RequestBody SysUserEntity sysUser) {
        if (sysUser.getId() == null) {
            // 默认密码
            String password = passwordEncoder.encode(Const.DEFAULT_PASSWORD);
            sysUser.setPassword(password);

            // 默认头像
            sysUser.setAvatar(Const.DEFAULT_AVATAR);

            sysUserService.save(sysUser);
            return Result.success(sysUser);
        }
        return Result.success(sysUserService.updateById(sysUser));
    }

    @ApiOperation("通过用户id删除用户")
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@RequestBody Long id) {
        sysUserService.removeById(id);
        sysUserRoleService.remove(Wrappers.lambdaQuery(SysUserRoleEntity.class).in(SysUserRoleEntity::getUserId, id));
        return Result.success("");
    }

    @ApiOperation("重置密码")
    @PostMapping("/resetPasswd")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    public Result resetPasswd(@RequestBody Long userId) {
        SysUserEntity sysUser = sysUserService.getById(userId);
        sysUser.setPassword(passwordEncoder.encode(Const.DEFAULT_PASSWORD));
        sysUserService.updateById(sysUser);
        return Result.success("");
    }

    /**
     * @Description: 更改密码
     * @Param: [passDto, principal]
     * @return: com.weishenai.blog.common.lang.Result
     * @Author: weishenai
     * @Date: 2021/12/14
     */
    @ApiOperation("更改密码")
    @PostMapping("/updatePass")
    public Result updatePass(@Validated @RequestBody PassDto passDto, Principal principal) {

        SysUserEntity sysUser = sysUserService.getByUsername(principal.getName());

        boolean matches = passwordEncoder.matches(passDto.getCurrentPass(), sysUser.getPassword());
        if (!matches) {
            return Result.failed("旧密码不正确");
        }
        sysUser.setPassword(passwordEncoder.encode(passDto.getPassword()));

        sysUserService.updateById(sysUser);
        return Result.success("");
    }


    /**
     * @Description: 为用户分配角色
     * @Param: [userId, roleIds]
     * @return: com.weishenai.blog.common.lang.Result
     * @Author: weishenai
     * @Date: 2021/12/13
     */
    @ApiOperation("为用户分配角色")
    @ApiImplicitParam(name = "userid",value="用户id")
    @PostMapping("/role/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public Result rolePerm(@PathVariable("userId") Long userId, @RequestBody Long[] roleIds) {
        List<SysUserRoleEntity> userRoles = new ArrayList<>();
        Arrays.stream(roleIds).forEach(r -> {
            SysUserRoleEntity sysUserRole = new SysUserRoleEntity();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(userId);

            userRoles.add(sysUserRole);
        });

        sysUserRoleService.remove(Wrappers.lambdaQuery(SysUserRoleEntity.class).eq(SysUserRoleEntity::getUserId, userId));
        sysUserRoleService.saveBatch(userRoles);

        // 删除缓存
        SysUserEntity sysUser = sysUserService.getById(userId);
        sysUserService.clearUserAuthorityInfo(sysUser.getUsername());
        return Result.success("");
    }

    @ApiOperation("更具用户id获取角色")
    @ApiImplicitParam(name = "userid",value = "用户id")
    @GetMapping("/role/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public Result getRoleByUserId(@PathVariable("userId") Long userId) {
        return Result.success(sysUserRoleService.getRolesByUserId(userId));
    }

    /**
     * @Description: 更新用户图标
     * @Param: []
     * @return: com.weishenai.blog.common.lang.Result
     * @Author: weishenai
     * @Date: 2021/12/14
     */
    @ApiOperation("更新用户图标")
    @PostMapping("/uploadIcon")
    public Result updateIcon(@RequestParam(value = "file") MultipartFile file, Principal principal) {
        if (file.isEmpty()) {
            return Result.failed("文件为空");
        }
        String name = principal.getName() + ".jpg";
        SysUserEntity sysUser = sysUserService.getByUsername(principal.getName());
        sysUser.setAvatar("userIcon/" + name);
        sysUserService.updateById(sysUser);
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        try {
            file.transferTo(new File(folder, name));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success("");
    }
}
